package com.example.mqtt.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEvent;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.lang.annotation.Annotation;
import java.util.Collections;
import java.util.Map;

@Component
public class ApplicationContextUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    private static String applicationName = "unInit";
    private static String APP_ID = "0";

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ApplicationContextUtil.applicationContext = applicationContext;
    }

    public static Map<String,Object> getBeanByAnnotation(Class<? extends Annotation> aClass) {
        if (applicationContext!=null) {
            return applicationContext.getBeansWithAnnotation(aClass);
        }
        return null;
    }

    public static Object getBean(String beanName) {
        if (applicationContext!=null) {
            return applicationContext.getBean(beanName);
        }
        return null;
    }

    public static Object getBean(String beanName,Class<?> clazz) {
        if (applicationContext!=null) {
            return applicationContext.getBean(beanName,clazz);
        }
        return null;
    }

    public static<T> Map<String, T> getBeans(Class<T> clazz) {
        if (applicationContext!=null) {
            return applicationContext.getBeansOfType(clazz);
        }
        return Collections.emptyMap();
    }



    public static void publishEvent(ApplicationEvent event) {
        if (applicationContext == null) {
            return;
        }
        applicationContext.publishEvent(event);
    }
    private static void setApplicationName() {
        if (applicationContext == null) {
            return;
        }
        String ENVIRONMENT = "spring.application.name";
        String intStr = applicationContext.getEnvironment().getProperty(ENVIRONMENT);
        if (!StringUtils.isEmpty(intStr)) {
            applicationName = intStr;
        }
    }

    public static String getApplicationName() {
        return applicationName;
    }
}
